// define(function(require) {

  var React = require('react');
  var Component = React.Component;
  var $ = require('js/util/deparam');
  var antd = require('antd');
  var { Form, Button, Input, Icon, message } = antd;
  var _ = require('lodash')
  var Select = require('jsx!./select')

  var SelectSeries = require('jsx!./select-series')

  const RT_COLLECTION = true;

  let store = null;
  const GOING_DOWN_OPTIONS = {
    EMBED_WEBPAGE: '0',
    EMBED_WINDOW: '1',
    EMBED_WIDGET: '2'
  }

  const openOptions = [
    {
      value: 'newPage',
      label: '新窗口打开'
    },
    {
      value: 'originalPage',
      label: '原窗口打开'
    }
  ];

  // 不需要下钻多个视图选项的
  const SingleSeries = [
    'text',
    'multi',
    'counter',
    'time',
    'gauge',
    'led',
    'container',
    'thermometer',
    'process'
  ]

  const goingdownOptions = [{
    value: GOING_DOWN_OPTIONS.EMBED_WEBPAGE,
    label: '内嵌WebPage'
  }, {
    value: GOING_DOWN_OPTIONS.EMBED_WINDOW,
    label: '内嵌新视图'
  }, {
    value: GOING_DOWN_OPTIONS.EMBED_WIDGET,
    label: '内嵌其他图表'
  }]

  const FormItem = Form.Item

  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  }

  class GoingdownSetting extends Component {

    constructor(props) {
      super(props);
      this.state = {
        collapse: false,
        dashboard: [],
        interact: props.interact
      }
    }

    componentDidMount() {
      if (this.props.windowList) {
        this.buildWindowListOption(this.props.windowList);
      }
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.id !== this.props.id) {
        this.setState({
          interact: nextProps.interact
        })
      }

      if (this.props.windowList !== nextProps.windowList && nextProps.windowList) {
        this.buildWindowListOption(nextProps.windowList);
      }
    }

    componentDidUpdate(prevProps, prevState) {
      if (prevState.interact !== this.state.interact) {
        this.props.form.resetFields()
      }
    }

    render() {
      const { getFieldDecorator } = this.props.form

      const interact = this.state.interact || {}
      const type = !isNaN(interact.type) ? String(interact.type) : undefined;

      return (
        <div className="goingdown-setting">
          <Form onSubmit={this.handleSubmit.bind(this)}>
            <FormItem {...formItemLayout} label={ '下钻' }>
              { getFieldDecorator('type', {
                initialValue: type
              })(
                <Select
                  options={goingdownOptions}
                  placeholder={'请选择下钻类型'}
                  notFoundContent={'没有可用选项'}
                  onChange={RT_COLLECTION ? this.handleChange.bind(this, 'type')
                  : this.handleChangeType.bind(this)} />
              )}
            </FormItem>

            { this.renderType(type, interact) }

            {
              RT_COLLECTION
              ? null
              : <FormItem {...formItemLayout}>
                  <Button type="primary" htmlType="submit">
                    Submit
                  </Button>
                </FormItem>
            }
          </Form>
        </div>
      )
    }

    handleChangeType(type) {
      let interact = this.state.interact || {}
      interact.type = type
      this.setState({ interact })
    }

    buildWindowListOption(windowList) {
      let dashboard = _.map(windowList, (window) => {
        return { value: window.id, label: window.title }
      });
      this.setState({ dashboard })
    }

    handleChange(key, value) {
      if (!RT_COLLECTION) return;
      let newValues = {};
      newValues[key] = value;
      let isViewUrl = key === 'clickContent(viewUrl)'
      if (isViewUrl && !this.isSingleSeries()) { // 当改变 viewUrl 时，viewUrls 应当相应改变
        const { clickContent = {} } = this.props.interact
        const viewUrls = this.getDefaultViewUrls(value, clickContent.viewUrls);
        newValues['clickContent(viewUrls)'] = viewUrls;
      }
      let data = $.deparamObj(newValues, true)
      data = _.merge({}, this.props.interact, data);
      this.setState({ interact: data }, () => {
        this.props.onChange(data)
        message.success('submit is ok')
      })
    }

    handleChangeUrl(key, e) {
      this.handleChange(key, e.target.value)
    }

    handleCollapse() {
      this.setState({
        collapse: !this.state.collapse
      })
    }

    enterEditor() {

    }

    /**
     * [getSeries 每个组件对应的series不一样, xAxis或yAxis等，从组件实例中获取]
     * @return {Array} [description]
     */
    getSeries() {
      
    }

    isSingleSeries() {
      return SingleSeries.includes(this.props.type)
    }

    /**
     * [isMutiSeleted 是否是多选]
     * @param  {[object]}  viewUrls [description]
     * @param  {String}  viewUrl  [description]
     * @return {Boolean}          [description]
     */
    isMutiSeleted(viewUrls, viewUrl) {
      if (!Array.isArray(viewUrls)) { return false }
      let isMuti = false
      let isUnique = false
      viewUrls.map((item) => {
        (item.value !== viewUrls[0].value) && (isMuti = true)
      })

      // 多选时各自选中了相同选项，但和全选选项不同，这时也会显示多选内容
      if (!isMuti && viewUrls[0] && (viewUrls[0].value !== viewUrl)) {
        isUnique = true
      }
      return isMuti || isUnique
    }

    /**
     * [getDefaultViewUrls 获取 viewUrls, 没有时则为空]
     * @param  {String} viewUrl [description]
     * @param  {Array} viewUrls [有数据时传入]
     * @return {Array}         [description]
     */
    getDefaultViewUrls(viewUrl, viewUrls) {
      let data = viewUrls || this.getSeries()
      return _.map(data, (item) => {
        return {
          name: viewUrls ? item.name : item,
          value: viewUrl ? viewUrl : ''
        }
      })
    }

    renderCollapse() {
      return (<Icon type={this.state.collapse ? 'up-circle' : 'down-circle'}
                    className="anticon-origin"
                    onClick={this.handleCollapse.bind(this)}
              />)
    }

    /**
     * [renderMutiSelected 选中项的显示]
     * @param  {[object]} viewUrls [description]
     * @return {Object}          [description]
     */
    renderMutiSelected(viewUrls) {
      return (
        <div className="collapse-selected" style={{display: 'inline-block'}}>
          <div className="collapse-selected-content">
            {viewUrls.map((item, index) => {
              let labelView = this.state.dashboard.find((view) => {
                return view.value === item.value
              })
              return (<div className={labelView ? 'selected-view' : 'selected-view-hidden'}
                           key={index}>
                        {labelView ? labelView.label : ''}
                      </div>)
            })}
          </div>
        </div>
      )
    }

    renderType(type, interact) {
      const { getFieldDecorator } = this.props.form
      let clickContent = interact.clickContent || {};
      let singleStyle = { width: '100%' }
      let mutiStyle = { width: '75%' }

      let components = [];

      switch (type) {
        case GOING_DOWN_OPTIONS.EMBED_WEBPAGE:
          components.push(
            <FormItem {...formItemLayout} key="webpageUrl"
              label={ '地址' }>
              { getFieldDecorator('clickContent(webpageUrl)', {
                initialValue: clickContent.webpageUrl || '',
                rules: [{
                  required: true,
                  message: '请输入地址'
                }, {
                  max: 20,
                  message: '最大20'
                },  {
                  min: 5,
                  message: '最小5'
                }]
              })(
                <Input
                  placeholder={'请填写第三方地址'}
                  onChange={this.handleChangeUrl.bind(this, 'clickContent(webpageUrl)')} />
              )}
            </FormItem>
          )
          break;
        case GOING_DOWN_OPTIONS.EMBED_WINDOW:
          components.push(
            <FormItem
              className="collapse-view" {...formItemLayout} key="viewUrl"
              label={'跳转至'}
            >
              {
                getFieldDecorator('clickContent(viewUrl)', {
                  initialValue: clickContent.viewUrl || undefined
                })
                (<Select
                  style={ this.isSingleSeries() ? singleStyle : mutiStyle }
                  options={this.state.dashboard}
                  placeholder={'请选择产品内视图名称'}
                  notFoundContent={'没有可用选项'}
                  onChange={this.handleChange.bind(this, 'clickContent(viewUrl)')}
                />)
              }
              {
                this.state.dashboard.length && clickContent.viewUrls
                  && this.isMutiSeleted(clickContent.viewUrls, clickContent.viewUrl) ?
                  this.renderMutiSelected(clickContent.viewUrls) : null
              }
              { // 部分单值组件不需要
                this.isSingleSeries() ? null : this.renderCollapse()
              }
            </FormItem>
          )
          // 如果表单元素没有，那么表单验证会遗漏这一项，导致每次输入元素都会重置 viewUrl
          // 所以这里只是隐藏元素，但实际上 dom 还存在
          if (!this.isSingleSeries()) {
            const visibileHidden = {
              width: 0,
              height: 0,
              margin: 0,
              overflow: 'hidden'
            }

            const viewUrls = clickContent.viewUrls;
            const viewUrl = clickContent.viewUrl;

            if (viewUrls === store) {
              console.log('equal')
            } else {
              console.log('not equal')
            }
            store = viewUrls;

            /**
             * [renderViewUrls 多项选择]
             * @param  {[object]} viewUrls [description]
             * @param  {String} viewUrl  [description]
             * @return {Object}          [description]
             */
            components.push(
              <FormItem {..._.merge({}, formItemLayout, { wrapperCol: {offset: 6}})} key="viewUrls" style={this.state.collapse ? {} : visibileHidden}>
              {
                getFieldDecorator('clickContent(viewUrls)', {
                  initialValue: viewUrls || this.getDefaultViewUrls(viewUrl)
                })
                (<SelectSeries
                  viewUrl={viewUrl}
                  form={this.props.form}
                  options={this.state.dashboard}
                  placeholder={'请选择产品内视图名称'}
                  notFoundContent={'没有可用选项'}
                  onChange={this.handleChange.bind(this, 'clickContent(viewUrls)')}
                />)
              }
              </FormItem>
            )
          }
          break;
        case GOING_DOWN_OPTIONS.EMBED_WIDGET:
          components.push(
            <FormItem {...formItemLayout} key="enterEditor"
              label={'状态'}>
              <Button type="primary" onClick={this.enterEditor.bind(this)}>
                { '进入编辑' }
              </Button>
            </FormItem>
          )
          break;
      }

      if (type === GOING_DOWN_OPTIONS.EMBED_WEBPAGE || type === GOING_DOWN_OPTIONS.EMBED_WINDOW) {
        components.push(
          <FormItem {...formItemLayout} key="openMethod"
            label={'打开方式'}>
            {
              getFieldDecorator('clickContent(openMethod)', {
                initialValue: clickContent.openMethod || undefined
              })
              (<Select
                options={openOptions}
                placeholder={'请选择展现方式'}
                notFoundContent={'没有可用选项'}
                onChange={this.handleChange.bind(this, 'clickContent(openMethod)')}
              />)
            }
          </FormItem>
        )
      }
      return components;
    }

    handleSubmit(e) {
      e.preventDefault();
      this.props.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values);
          message.success('submit is ok')
        }
      });
    }
  }

  GoingdownSetting = Form.create()(GoingdownSetting)

  module.exports = GoingdownSetting

// })